import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../views/user/login.vue'
import home from '../views/home/home.vue'
import movie from '../views/movie/movie.vue'
import qa from '../views/qa/qa.vue'
import user from '../views/user/user.vue'
import notfound from '../views/notfound/notfound.vue'
import eait from '../views/user/eait.vue'
import student from '../views/user/student.vue'
import articles from '../views/home/articles.vue'
import search from '../views/home/search.vue'
import searchRuslt from '@/views/home/searchRuslt.vue'
Vue.use(VueRouter)

const routes = [
  {
    name: 'login',
    path: '/login',
    component: login
  }, {
    name: 'home',
    path: '/home',
    component: home,
    meta: { showTab: true }
  }, {
    name: 'movie',
    path: '/movie',
    component: movie,
    meta: { showTab: true }
  }, {
    name: 'qa',
    path: '/qa',
    component: qa,
    meta: { showTab: true }
  }, {
    name: 'user',
    path: '/user',
    component: user,
    meta: { showTab: true, isLogin: true }
  },
  {
    name: 'notfound',
    path: '/notfound',
    component: notfound,
  }, {
    name: 'eait',
    path: '/eait',
    component: eait,
  }, {
    name: 'student',
    path: '/student',
    component: student,
  },
  {
    name: 'articles',
    path: '/articles',
    component: articles,
  },
  {
    name: 'search',
    path: '/search',
    component: search,
  },
  {
    name: 'searchRuslt',
    path: '/searchRuslt',
    component: searchRuslt,
  },
  //重定向
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '*',
    redirect: '/notfound'
  }
]

/* 去掉路由跳转reject异常提示
注意：我们是直接修改VueRouter的原型，所以需要在实例化之前调用
*/
//(1)先保存路由原型链中默认的跳转函数
const originalPush = VueRouter.prototype.push
//(2)替换原型链中的push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    // 正常执行
    //originalPush.call() : 我们自定义的push底层还是调用默认的push
    return originalPush.call(this, location, onResolve, onReject)
  }
  //如果有异常，本来这个err默认是抛出的，我们直接不做任何处理（给吞掉了）
  /* 
  底层默认是抛出异常：err => {throw err}
  我们不抛出，不做任何处理：err => err
  */
  return originalPush.call(this, location).catch(err => err)
}

/*吞异常提示，需要在创建路由实例之前，就给原型链添加哈*/
const router = new VueRouter({
  routes
})

//引入token配置
import { getToken } from '@/utils/token.js'
//配置路由守卫
router.beforeEach((to, from, next) => {
  // 如果to中带ture 与 没有令牌的情况则跳到指定页面
  if (to.meta.isLogin && !getToken()) {
    // 没有登陆 跳到登陆页  next必须调用
    next({ path: '/login' })
  } else {
    //有登陆则放行
    next()
  }
})
export default router
